<?php


// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
error_reporting ( E_ERROR | E_PARSE );

function goods_flag() {
	return array ('tj' => '推荐' );
}
function get_client_ip() {
	if (getenv ( "HTTP_CLIENT_IP" ) && strcasecmp ( getenv ( "HTTP_CLIENT_IP" ), "unknown" )) {
		$ip = getenv ( "HTTP_CLIENT_IP" );
	} else if (getenv ( "HTTP_X_FORWARDED_FOR" ) && strcasecmp ( getenv ( "HTTP_X_FORWARDED_FOR" ), "unknown" )) {
		$ip = getenv ( "HTTP_X_FORWARDED_FOR" );
	} else if (getenv ( "REMOTE_ADDR" ) && strcasecmp ( getenv ( "REMOTE_ADDR" ), "unknown" )) {
		$ip = getenv ( "REMOTE_ADDR" );
	} else if (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], "unknown" )) {
		$ip = $_SERVER ['REMOTE_ADDR'];
	} else {
		$ip = "unknown";
	}
	return ($ip);
}
function randomkeys($length) {
	$pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
	for($i = 0; $i < $length; $i ++) {
		$key .= $pattern {mt_rand ( 0, 35 )};
	}
	return $key;
}
function array_sort($arr, $keys, $orderby = 'asc') {
	$keysvalue = $new_array = array ();
	foreach ( $arr as $k => $v ) {
		$keysvalue [$k] = $v [$keys];
	}
	if ($orderby == 'asc') {
		asort ( $keysvalue );
	} else {
		arsort ( $keysvalue );
	}
	reset ( $keysvalue );
	foreach ( $keysvalue as $k => $v ) {
		$new_array [] = $arr [$k];
	}
	return $new_array;
}
function GetCurrentHost($blogpath, &$cookiespath) {
	$host = '';
	if (array_key_exists ( 'REQUEST_SCHEME', $_SERVER )) {
		if (strtolower ( $_SERVER ['REQUEST_SCHEME'] ) == 'https') {
			$host = 'https://';
		} else {
			$host = 'http://';
		}
	} elseif (array_key_exists ( 'HTTPS', $_SERVER )) {
		if (strtolower ( $_SERVER ['HTTPS'] ) == 'on') {
			$host = 'https://';
		} else {
			$host = 'http://';
		}
	} else {
		$host = 'http://';
	}
	$host .= $_SERVER ['HTTP_HOST'];
	$x = $_SERVER ['SCRIPT_NAME'];
	$y = $blogpath;
	if (isset ( $_SERVER ["CONTEXT_DOCUMENT_ROOT"] ) && isset ( $_SERVER ["CONTEXT_PREFIX"] ))
		if ($_SERVER ["CONTEXT_DOCUMENT_ROOT"] && $_SERVER ["CONTEXT_PREFIX"]) {
			$y = $_SERVER ["CONTEXT_DOCUMENT_ROOT"] . $_SERVER ["CONTEXT_PREFIX"] . '/';
		}
	$z = '';
	for($i = strlen ( $x ); $i > 0; $i --) {
		$z = substr ( $x, 0, $i );
		if (strtolower ( substr ( $y, strlen ( $y ) - $i ) ) == strtolower ( $z )) {
			break;
		}
	}
	$cookiespath = $z;
	return $host . $z;
}

function http_request($data, $multi = false){
    if(!isset($data['url']) && ($tmp = current($data)) && isset($tmp['url'])){
        if($multi){
            //curl并发模式
            $mch = curl_multi_init();

            $ch = $ret = $error = [];
            foreach($data as $k => $v){
                $v['return_curl'] = true;
                $ch[$k] = http_request($v);
                $ret[$k] = ['head' => '', 'body' => null];

                curl_multi_add_handle($mch, $ch[$k]);
            }

            $active = null;
            //execute the handles
            do {
                $mrc = curl_multi_exec($mch, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);

            while ($active && $mrc == CURLM_OK) {
                if (curl_multi_select($mch) != -1) {
                    do {
                        $mrc = curl_multi_exec($mch, $active);
                        $info = curl_multi_info_read($mch);
                        if($info !== false && $info['result']){
                            foreach($ch as $k => $v){
                                if($v === $info['handle']){
                                    $tmp = curl_getinfo($info['handle']);
                                    $error[$k] = [$info['result'], curl_error($info['handle']), $tmp['url']];
                                    break;
                                }
                            }
                        }
                    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
                }
            }

            $error_log = '';
            foreach($ch as $k => $v){
                if(isset($error[$k])){
                    $ret[$k]['body'] = null;
                    $ret[$k]['info']['status'] = 0;
                    $ret[$k]['info']['errno'] = $error[$k][0];
                    $error_log .= "{$error[$k][2]}|{$error[$k][0]}|{$error[$k][1]}\n";

                    continue;
                }

                $ret[$k]['body'] = curl_multi_getcontent($v);

                $info = curl_getinfo($v);
                $ret[$k]['info']['status'] = $info['http_code'];
                curl_multi_remove_handle($mch, $ch[$k]);
            }

            if(!empty($error)){
                var_dump($error_log);
            }

            curl_multi_close($mch);

            return $ret;

        }else{
            $ret = [];
            foreach($data as $k => $v){
                $ret[$k] = http_request($v);
            }
            return $ret;
        }
    }

    $data['post'] = isset($data['post']) ? $data['post'] : '';
    $data['cookie'] = isset($data['cookie']) ? $data['cookie'] : '';
    $data['ip'] = isset($data['ip']) ? $data['ip'] : '';
    $data['timeout'] = isset($data['timeout']) ? $data['timeout'] : 15;
    $data['block'] = isset($data['block']) ? $data['block'] : true;
    $data['referer'] = isset($data['referer']) ? $data['referer'] : '';
    $data['connection'] = isset($data['connection']) ? $data['connection'] : 'close';
    $data['header'] = isset($data['header']) ? (array)$data['header'] : [];
    $data['retry'] = isset($data['retry']) ? $data['retry'] : 2;
    var_dump($data);
    $ch = curl_init($data['url']);

    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    //curl_setopt($ch, CURLOPT_ACCEPT_ENCODING, 'gzip');
    curl_setopt($ch, CURLOPT_USERAGENT, !empty($data['UA']) ? $data['UA'] : '');
    if(!empty($data['debug'])){
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        $fp = fopen($data['debug'], 'a');
        curl_setopt($ch, CURLOPT_STDERR, $fp);
        //fclose($fp);
    }
    //curl_setopt($ch, CURLOPT_ENCODING, 'none');

    curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($data['header'], [
        'Connection: '. $data['connection']
    ]));

    if(stripos($data['url'], 'https://') === 0){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
        //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }

    if(!empty($data['referer'])) curl_setopt($ch, CURLOPT_REFERER, $data['referer']);
    if(!empty($data['cookie'])) curl_setopt($ch, CURLOPT_COOKIE, $data['cookie']);
    if(!empty($data['cookie_file'])) curl_setopt($ch, CURLOPT_COOKIEFILE, $data['cookie_file']);
    if(!empty($data['save_cookie'])) curl_setopt($ch, CURLOPT_COOKIEJAR, $data['save_cookie']);
    if(!empty($data['proxy'])) curl_setopt($ch, CURLOPT_PROXY, $data['proxy']);

    if(!empty($data['post'])){
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data['post']);
    }

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $data['timeout']);
    curl_setopt($ch, CURLOPT_TIMEOUT, $data['timeout']);
    if(!empty($data['option'])){
        curl_setopt_array($ch, $data['option']);
    }

    if(!empty($data['return_curl'])) return $ch;

    $i = 0;
    while($i < $data['retry']){
        if(($ret = curl_exec($ch)) !== false) break;

        $ret = null;
        ++$i;
        if($errno = curl_errno($ch)){
            $error = curl_error($ch);

            $s = "$data[url]|$errno|$error|retry:$i";
            if(isset($data['log']) && $data['log'] == 'local'){
                var_dump( $s);
            }else{
                var_dump( $s);
            }
        }
    }

    $info = curl_getinfo($ch);
    curl_close($ch);

    return ['head' => '', 'body' => $ret, 'info' => [
        'status' => $info['http_code'],
        'errno' => !empty($errno) ? $errno : '',
        'error' => !empty($error) ? $errno : '',
        'retry' => $i
    ]];
}

function get_config(){
    return [
        'APPID' => 'RPFYC4XQJBC2J2S3',
        'AccessKeySecret' => 'NDGWC7AIRBBHLEAG6J92YXFMGGC0TA7C',
        'gateway' => 'https://api.trc20api.com',
    ];
}